package com.example.demo.channel;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.demo.config.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.Map;

/**
 * @PackageName: com.example.demo.channel
 * @ClassName: RedisMessageSubscriber
 * @Description:
 * @Author: czl
 * @Date: 2025/7/27 15:40
 */
@Component
public class RedisMessageSubscriber implements MessageListener {
    private static final Logger log = LoggerFactory.getLogger(RedisMessageSubscriber.class);

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel());
        String msg = new String(message.getBody());
        log.info("接受redis频道消息 [" + channel + "]: " + msg);
        JSONObject jsonObject = JSON.parseObject(msg);
        String msgInfo = jsonObject.getString("msg");
        String sessionId = jsonObject.getString("sessionId");
        Map<String, Session> clientMap = WebSocketServer.clientMap;
        if (sessionId != null && clientMap.containsKey(sessionId)) {
            Session session = clientMap.get(sessionId);
            log.info("redis -> 推送消息 message:{}, sessionID: {},port:{}", msgInfo, session.getId(), WebSocketServer.serverPort);
            session.getAsyncRemote().sendText(msgInfo);
        }

    }
}
